package com.csun.cmny.provider.task;

import com.csun.cmny.provider.model.domain.OpcAppClock;
import com.csun.cmny.provider.service.OpcAppClockService;
import com.csun.cmny.provider.service.impl.JPushService;
import com.csun.cmny.util.DateUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2020-04-20 11:21
 * @Description:
 */
@Slf4j
public class AppClockQuartz extends QuartzJobBean {

    @Resource
    private OpcAppClockService opcAppClockService;
    @Resource
    private JPushService jPushService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        Date date = new Date();

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        // 获取周期
        int w = cal.get(Calendar.DAY_OF_WEEK) - 2;
        if (w == -1) {
            w = 6;
        }

        String str = DateUtil.YYYY_MM_DD_MM_HH_SS.format(date);
        String time = str.substring(11, 16);

        log.info("定时推送APP闹钟 ==》 {}, 周数 = {}， 时间 = {}", DateUtil.dateToString(date), w, time);

        OpcAppClock opcAppClock = new OpcAppClock();
        opcAppClock.setOpen(1);
        opcAppClock.setTime(time);
        List<OpcAppClock> opcAppClockList = opcAppClockService.select(opcAppClock);
        for (OpcAppClock c : opcAppClockList) {
            log.info("app clock ==> {}", c.toString());
            if (c.getRepeat().split("-")[w].equals("1")) {
                // 推送闹钟
                Map map = JSONObject.fromObject(c);
                map.put("msgType", "appClock");
                List<String> tagList = Lists.newArrayList("userId_" + c.getUserId());
                //
                String sound = "sound.caf";
                if (c.getBell().equals(1)) {
                    sound = "lightM_1.caf";
                }
                jPushService.sendToAll(c.getTitle(), c.getTitle(), c.getTitle(), map.toString(), tagList, sound);
            }
        }
    }
}
